package pyf.demo12;

/**
 * @author pengyifeng
 * @version 5.1
 * @ClassName DeadLockDemo.java
 * @Description 避免死锁示例 避免资源相互调用
 * 注释部分为错误写法，造成死锁
 * @createTime 2021年07月27日 13:53:00
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        new Use(0,"小明").start();
        new Use(1,"小红").start();
    }
/**
 * 资源一
 */
static class One{}

/**
 * 资源二
 */
static class Two{}

static class Use extends Thread{

     static One one=new One();
     static Two two=new Two();

     //选择
     int choice;
     //使用人
    String name;

    Use(int choice,String name){
        this.choice=choice;
        this.name=name;
    }
    private void startUse(){
        //if(0==choice){
        //    synchronized (one){
        //        System.out.println(this.name+"获得资源One");
        //        try {
        //            Thread.sleep(1000);
        //        } catch (InterruptedException e) {
        //            e.printStackTrace();
        //        }
        //        synchronized (two){
        //            System.out.println(this.name+"获取资源Two");
        //        }
        //    }
        //}else {
        //    synchronized (two){
        //        System.out.println(this.name+"获得资源two");
        //        try {
        //            Thread.sleep(2000);
        //        } catch (InterruptedException e) {
        //            e.printStackTrace();
        //        }
        //        synchronized (one){
        //            System.out.println(this.name+"获取资源one");
        //        }
        //    }
        //}
        if(0==choice){
            synchronized (one){
                System.out.println(this.name+"获得资源One");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            synchronized (two){
                System.out.println(this.name+"获取资源Two");
            }
        }else {
            synchronized (two){
                System.out.println(this.name+"获得资源two");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            synchronized (one){
                System.out.println(this.name+"获取资源one");
            }
        }
    }
    @Override
    public void run() {
        startUse();
    }
}
}
